import qiniu from "qiniu";
const accessKey = 'JUamKcvBktrWmDbq-CCxfLYxbCOqAjdIciKaYbUc';
const secretKey = 'ZJM4NzyIHB07-hWhvp8VeU8wyaL75Xg9QGdcBW7w';
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const bucket = 'micr0video';
const options = {
    scope: bucket,
    returnBody: '{"host":"http://assert.auage.cc/","key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)","age":$(x:age)}',
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);
const config = new qiniu.conf.Config({
    zone: qiniu.zone.Zone_z0,
});
export function getToken() {
    const token = putPolicy.uploadToken(mac);
    return token;
}
export function uploadFile(readableStream: any) {
    const formUploader = new qiniu.form_up.FormUploader(config);
    const putExtra = new qiniu.form_up.PutExtra();
    const key = new Date().getTime() + (Math.random() * 10).toFixed(0);
    return new Promise((resolve, reject) => {
        formUploader.putStream(uploadToken, key, readableStream, putExtra, (respErr, respBody, respInfo) => {
            if (respErr) {
                reject(respErr);
                return;
            }
            if (respInfo.statusCode === 200) {
                resolve(respInfo);
            }
        });
    }); 
}
export function uploadFiles(readableStreams: any) {
    const formUploader = new qiniu.form_up.FormUploader(config);
    const putExtra = new qiniu.form_up.PutExtra();
    return Promise.all(readableStreams.map((readableStream: any) => (
        new Promise((resolve, reject) => {
            const key = new Date().getTime() + (Math.random() * 10).toFixed(0) + '.' + readableStream.ext;
            formUploader.putStream(uploadToken, key, readableStream.file, putExtra, (respErr, respBody, respInfo) => {
                if (respErr) {
                    reject(respErr);
                    return;
                }
                if (respInfo.statusCode === 200) {
                    resolve({
                        ...respInfo.data,
                        filename: readableStream.filename,
                    });
                } else {
                    reject('上传失败');
                }
            });
        })
    )));
}

export function deleteFile(key: string) {
    const bucketManager = new qiniu.rs.BucketManager(mac, config);
    return new Promise((resolve, reject) => {
        bucketManager.delete(bucket, key, (err, respBody, respInfo) => {
            if (err) {
                console.log('delete err===>', err);
                reject(err);
            } else {
                if (respInfo.statusCode === 200) {
                    resolve('删除成功');
                } else {
                    reject('删除失败');
                }
                
            }
        });
    });
}